package com.sajus.web.billing.ejb.bean;

import javax.persistence.EntityManager;

/**
 * the class is used to pass the transaction context to 
 * the business methods. The transaction context is 
 * initialized by the EJB and committed/closed by the EJB
 * 
 * @author nicolara
 *
 */
public class TransactionContext {

	private EntityManager em;
	private boolean isLocalManaged = false;
	
	public EntityManager getEm() {
		return em;
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}

	static private ThreadLocal<TransactionContext> local = new ThreadLocal<TransactionContext>();

	static public TransactionContext getTransactionContext() {
		return local.get();
	}

	static public void setTransactionContext( TransactionContext ctx) {
		local.set(ctx);
	}

	public TransactionContext(EntityManager em ) {
		super();
		this.em = em;
		setTransactionContext( this );
	}
	
	public void close() {
		if ( em != null && em.isOpen() && isLocalManaged() ) {
			em.close();
		}
	}

	public boolean isLocalManaged() {
		return isLocalManaged;
	}

	public void setLocalManaged(boolean isLocalManaged) {
		this.isLocalManaged = isLocalManaged;
	}

}
